package com.example.s202404027;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("/d1")
public class Demo1 {
    @RequestMapping("/getC1")
    public String getCookie1(HttpServletRequest request, HttpServletResponse response) {
        //获取参数
        String name = request.getParameter("name");
        //获取所有参数
        Cookie[] cookies = request.getCookies();
        //不使用lambda表达式
        StringBuilder stringBuilder = new StringBuilder();
        if(cookies != null) {
            for(Cookie ck : cookies) {
                stringBuilder.append(ck.getName() + ":" + ck.getValue());
            }
        }
        //return "获取Cookie信息:" + stringBuilder;

        //使用lambda表达式
        if(cookies != null) {
            Arrays.stream(cookies).forEach(ck -> System.out.println(ck.getName() + ":" + ck.getValue()));
        }
        return "获取Cookie";
    }

    @RequestMapping("/getC2")
    public String getCookie2(@CookieValue("name") String newName) {
        return "从Cookie中获取值，name:" + newName;
    }

    @RequestMapping("/setSess")
    public String setSess(HttpServletRequest request) {
        //从Cookie中获取到SessionId，根据SessionId获取Session对象，如果没有，就会创建一个
        HttpSession session = request.getSession();
        session.setAttribute("name", "zhangsan");
        return "设置Session成功";
    }

    @RequestMapping("getSess1")
    public String getsSess(HttpServletRequest request) {
        //从cookie中获取到了sessionID, 根据sessionID获取Session对象取Session对象,如果session不存在，不会自动创建
        HttpSession session = request.getSession(false);
        String userName = (String) session.getAttribute("name");
        return "name: " + userName;
    }

    @RequestMapping("getSess2")
    public String getSess2(HttpSession session) {
        String name = (String)session.getAttribute("name");
        return "从Session中获取name: " + name;
    }

    @RequestMapping("getSess3")
    public String getSess3(@SessionAttribute("name") String name) {
        return "从Session中获取name: " + name;
    }

    @RequestMapping("getHeader1")
    public String getHeader1(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "从Header获取信息，userAgent:" + userAgent;
    }

    @RequestMapping("getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent) {
        return "从Header获取信息，userAgent:" + userAgent;
    }
}
